/**
 * 与表单相关的方法
 * 
 * @author Matrix-J
 */

var EXForm = function() {
	"use strict";// 严格模式

	/** 用用于存储formMap 对象 */
	var formMap = {};

	return {
		/** 添加一个EXForm */
		addForm : function(exform) {
			formMap[exform.formId] = exform;
		},
		/** 获取一个EXForm */
		getForm : function(formId) {
			return formMap[formId];
		},
		// 验证一个form表格
		validform : function(fomNode) {
			var exForm = $(fomNode).Validform({
				tiptype : 2,
			});
			return exForm;
		},
		/**
		 * form表单数据转json
		 */
		toJson : function(form) {
			var result = {};
			var fieldArray = $(form).serializeArray();
			for (var i = 0; i < fieldArray.length; i++) {
				var field = fieldArray[i];
				if (field.name in result) {
					result[field.name] += "," + field.value;
				} else {
					result[field.name] = field.value;
				}
			}
			return result;
		},
		/**
		 * 表单提交前，初始化一些必要的事情
		 */
		initForm : function(param) {
			var exform = {
				beforeSubnit:null,
				formId : "dataform",
				isvalid : true,
				refresh:null//刷新数据回调函数
			}
			if (param) {
				exform = $.extend(exform, param);
			}
			if (exform.isvalid) {
				exform["validform"] = EXForm.validform("#" + exform.formId);
			}
			exform["submitUrl"] = $("#" + exform.formId).attr("action");
			exform["jform"] = $("#" + exform.formId);
			exform["layerIndex"] = parent.layer.getFrameIndex(window.name);
			EXForm.addForm(exform);
		},
		/**
		 * 提交表单数据
		 */
		submit : function(formId) {
			if (!formId) {
				formId = "dataform";
			}
			var exform = EXForm.getForm(formId);
			if (exform.validform.check()) {
				if(exform.beforeSubnit){
					exform.beforeSubnit();
				}
				$.AjaxProxy({
					p : EXForm.toJson("#" + exform.formId)
				}).invoke(exform.submitUrl, function(loj) {
					layer.alert(loj.getValue("info"), {
						icon : 1
					}, function(inindex) {
						// 关闭提示层
						layer.close(inindex);
						// 自定义刷新回调
						if (exform.refresh) {
							exform.refresh();
						} else if (parent.exGrid) {
							// 刷新表格
							parent.exGrid.loaDData();
						} 
						// 关闭iframe层
						parent.layer.close(exform.layerIndex);
					});
				});
			}
		}
	}
}();
